import axios from "axios";
// import { useNavigate } from 'react-router-dom'
import {
  baseURL,
  contentType,
  invalidCode,
  loginInterception,
  noPermissionCode,
  requestTimeout,
  successCode,
} from "@/utils/config";
// import qs from 'qs'
// import router from '@/router'
import { isArray } from "./validate";
import { showErrorToast } from "./customToast";
let loadingInstance;
const whiteList = ["/login"];
/**
 * @author https://github.com/zxwk1998/vue-admin-better （不想保留author可删除）
 * @description 处理code异常
 * @param {*} code
 * @param {*} msg
 */
const handleCode = (code, msg) => {
  return new Promise((resolve, reject) => {
    switch (code) {
      case invalidCode:
        showErrorToast(`${msg || '后端接口' + code + '异常'}`);
        reject(new Error(msg));
        if (loginInterception) {
          location.reload();
        }
        break;
      case noPermissionCode:
        showErrorToast(`${msg || '后端接口' + code + '异常'}`);
        reject(new Error(msg));
        if (loginInterception) {
          location.reload();
        }
        break;
      case 401001: // 未登录
        showErrorToast(`${msg}`);
        window.location.href = "/#/login";
        reject(new Error(msg));
        break;
      case 200016: // 消息上限
        showErrorToast(`${msg}`);
        reject(new Error(msg));
        break;
      case 200007: // 模型不存在
        showErrorToast(`${msg}`);
        reject(new Error(msg));
        break;
      case 200023: // 模型不存在
        showErrorToast(`${msg}`);
        reject(new Error(msg));
        break;  
      default:
        showErrorToast(`${msg}`);
        reject(new Error(msg));
        break;
    }
  });
};

const instance = axios.create({
  baseURL,
  timeout: requestTimeout,
  headers: {
    "Content-Type": contentType,
  },
});

instance.interceptors.request.use(
  (config) => {
    if (whiteList.includes(config.url)) {
      return config;
    }
    const token = localStorage.getItem("access_token");
    if (token) {
      config.headers["Authorization"] = `bearer ${token}`;
      config.headers["auth_header"] = `Basic cm9vdDpyb290`;
    }
    //这里会过滤所有为空、0、false的key，如果不需要请自行注释
    // if (config.data) config.data = Vue.prototype.$baseLodash.pickBy(config.data, Vue.prototype.$baseLodash.identity)
    // if (config.data && config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8')
    //   config.data = qs.stringify(config.data)
    // if (debounce.some((item) => config.url.includes(item))) loadingInstance = Vue.prototype.$baseLoading()
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (response) => {
    if (loadingInstance) loadingInstance.close();
    const { data, config } = response;
    const { code, message, msg } = data;
    // 操作正常Code数组
    const codeVerificationArray = isArray(successCode)
      ? [...successCode]
      : [...[successCode]];
    // 是否操作正常
    if (codeVerificationArray.includes(code)) {
      // TODO 这里需要根据后端返回的data数据结构进行判断
      // return data.data
      if (data.data) {
        return data.data;
      } else {
        return data;
      }
    } else {
      return handleCode(code, message || msg).catch((error) => {
        return Promise.reject(
          `vue-admin-beautiful请求异常拦截:${JSON.stringify({
            url: config.url,
            code,
            message: message || msg,
          })}` || "Error"
        );
      });
    }
  },
  (error) => {
    if (loadingInstance) loadingInstance.close();
    console.log("🚀 ~ error:", error);
    const { response, message, config } = error;
    
    if (error.response && error.response.data) {
      const { status, data } = response;
      
      // 特殊处理：针对聊天生成接口的 400 错误
      if (status === 400 && config && config.url) {
        const chatGenerateUrl = `${import.meta.env.VITE_BASE_URL}/user/chat/new/generate`;
        
        // 检查是否是聊天生成接口
        if (config.url === chatGenerateUrl || config.url.includes('/api/user/chat/new/generate')) {
          console.log("🚀 ~ 聊天接口400错误特殊处理:", { status, data });
          
          // 判断是否是需要Toast提示的特定错误码
          const specialErrorCodes = [200014, 200016,200023,200030];
          const errorCode = data.code;
          
          if (specialErrorCodes.includes(errorCode)) {
            // 特定错误码：显示Toast提示并拒绝Promise
            console.log("🚀 ~ 特定错误码Toast提示:", errorCode);
            return handleCode(status, data.msg || data.message || message);
          } else {
            // 其他400错误：直接抛出异常，让上层catch处理
            console.log("🚀 ~ 其他400错误，抛出异常供上层处理:", errorCode);
            return Promise.reject(error);
          }
        }
      }
      
      // 非聊天接口或非400错误：使用原有的错误处理逻辑
      return handleCode(status, data.msg || data.message || message);
    } else {
      let { message } = error;
      if (message === "Network Error") {
        message = "网络连接异常,请检查网络";
      }
      if (message.includes("timeout")) {
        message = "加载慢，请刷新";
      }
      if (message.includes("Request failed with status code")) {
        const code = message.substr(message.length - 3);
        message = `后端接口${code}异常`;
      }
      return new Promise((resolve, reject) => {
        showErrorToast(`${message}`);
        reject(error);
      });
    }
  }
);

export default instance;
